<?php
/**
 * Created by PhpStorm.
 * User: lanyun
 * Date: 16/4/4
 * Time: 下午3:35
 */
function writeLog($msg){
    date_default_timezone_set("Asia/Shanghai");
    file_put_contents('deploy_log.txt',"\r\n".date("Y-m-d H:i:s").':'.$msg,FILE_APPEND|LOCK_EX);
}

$descriptorspec = array(
    0 => array(
        "pipe",
        "r"
    ),
    1 => array(
        "pipe",
        "w"
    ),
    2 => array(
        "file",
        __DIR__ . "/deploy_log.txt",
        "a"
    )
);

//在webhooks上设置的密码
$password = 'in#d2n4x*and';

$postData = json_decode($_POST['hook'], true);
if($postData['password'] !== $password){
    writeLog('un-authorization request:'.$_SERVER['HTTP_HOST']);
    die;
} else {
    writeLog('authorization request:'.$_SERVER['HTTP_HOST']."\r\n");
}

//网站目录的绝对路径
//$cwd = '/data/wwwroot/autodeploy';
$cwd = __DIR__;
//远程分支
$updateUrl = 'origin master';

$processes[0] = proc_open('touch deploy_log.txt',$descriptorspec,$pipes,__DIR__,NULL);
//$processes[1] = proc_open('touch deploy_log.txt',$descriptorspec,$pipes,__DIR__,NULL);
//拉取项目
$processes[1] = proc_open('git pull '.$updateUrl,$descriptorspec,$pipes,$cwd,NULL);

$count = count($processes);
for($i = 0; $i < $count; $i++){
    if(is_resource($processes[$i])){
        $return_value = proc_close($processes[$i]);
    }

    if($return_value == 0){
        $result[$i] = true;
    }else{
        $result[$i] = false;
    }
}
for($i = 0; $i < $count; $i++){
    if($result[$i]){
        writeLog('Command '.$i.' success.');
    }else{
        writeLog('Command '.$i.' faild.');
    }
}
